package com.crazyauntzhang.easyshopbackend.controller;

import com.crazyauntzhang.easyshopbackend.domain.User;
import com.crazyauntzhang.easyshopbackend.request.EditPersonalInfoRequest;
import com.crazyauntzhang.easyshopbackend.result.ResponseResult;
import com.crazyauntzhang.easyshopbackend.service.UserService;
import com.crazyauntzhang.easyshopbackend.util.Token;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PersonalCenterController {

	private final UserService userService;

	@Autowired
	public PersonalCenterController(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 已登录用户查看个人信息
	 *
	 * @param token 请求头token
	 * @return 响应体
	 */
	@PostMapping("/showLoginUserInfo")
	public ResponseResult<Object> showLoginUserInfo(@RequestHeader("Authorization") String token) {
		Claims claims = Token.parseToken(token);
		String userID = (String) claims.get("userID");
		User user = userService.findUserById(userID, true);
		return new ResponseResult<>(10200, "OK", user);
	}

	/**
	 * 修改个人信息
	 *
	 * @param editPersonalInfoRequest 请求体
	 * @return 响应体
	 */
	@PostMapping("/editPersonalInfo")
	public ResponseResult<Object> editPersonalInfo(@RequestBody EditPersonalInfoRequest editPersonalInfoRequest) {
		String userID = editPersonalInfoRequest.getUserID();
		String username = editPersonalInfoRequest.getUsername();
		String password = editPersonalInfoRequest.getPassword();
		String tel = editPersonalInfoRequest.getTel();
		User user = userService.findUserById(userID, Boolean.TRUE);
		if (user == null)
			return new ResponseResult<>(10404, "User Not Found");
		if (username == null || username.isBlank())
			username = user.getUsername();
		if (password == null || password.isBlank())
			password = user.getRoleID();
		if (tel == null || tel.isBlank())
			tel = user.getTel();
		userService.changeUser(userID, userID, username, password, user.getRoleID(), user.getIsOnJob(), tel, user.getHireDate());
		User editedUser = new User(userID, username, password, user.getRoleID(), user.getIsOnJob(), tel, user.getHireDate());
		return new ResponseResult<>(10200, "OK", editedUser);
	}

}
